﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.IO;
using System.Web.Mvc;

namespace OAclient.Filters
{
    public class ExceptionFilter : ActionFilterAttribute, IExceptionFilter
    {
        //获取存放在配置文件中的异常日志存放路径
        string logPath = ConfigurationManager.AppSettings["ExpLogPath"].ToString() + "ExLog_" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
        static object _object = new object();
        /// <summary>
        /// 写入异常日志
        /// </summary>
        /// <param name="controller">controller名称</param>
        /// <param name="action">action名称</param>
        /// <param name="exMessage">异常信息</param>
        /// <param name="ip">客户端ip</param>
        void WriteExLog(string controller, string action, string exMessage, string ip)
        {
            string root_logpath = HttpContext.Current.Request.MapPath(ConfigurationManager.AppSettings["ExpLogPath"].ToString());
            if (!Directory.Exists(root_logpath))
                Directory.CreateDirectory(root_logpath);
            //获取站点相对路径
            string path = HttpContext.Current.Request.MapPath(logPath);

            lock (_object)
            {
                //通过文件流写入日志
                using (FileStream fs = new FileStream(path, FileMode.Append))
                {
                    using (StreamWriter writer = new StreamWriter(fs))
                    {
                        //写入异常信息
                        writer.WriteLine("################# Begin #################");
                        writer.WriteLine("Time:[{0}]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        writer.WriteLine("Controller:{0}", controller);
                        writer.WriteLine("Action:{0}", action);
                        writer.WriteLine("ExMessage:{0}", exMessage);

                        //writer.WriteLine("Operating System version is:{0}", System.Environment.OSVersion.Version.ToString());
                        //writer.WriteLine("Current Thread ID is:{0}", AppDomain.GetCurrentThreadId());

                        //此处为获取CLR的线程ID，非Windows线程，不可用
                        //Thread t = new Thread(new ThreadStart(WriteExLog));
                        //writer.WriteLine("Current Thread ID is:{0}", t.ManagedThreadId);

                        writer.WriteLine("############### Over ###############");
                    }
                }
            }
        }

        //void WriteExLog() { }

        /// <summary>
        /// 重写IExceptionFilter的发生异常的方法
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnException(ExceptionContext filterContext)
        {
            //获取客户端ip
            string ip = (filterContext.HttpContext.Request.ServerVariables["HTTP_VIA"] != null) ? System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            //调用写入异常日志的方法
            WriteExLog(filterContext.RouteData.Values["controller"].ToString(),
                filterContext.RouteData.Values["action"].ToString(),
                filterContext.Exception.Message, ip);


        }
    }
}
